
import 'package:flutter/material.dart';
import 'package:flutter_fun_zjversion/model/article.dart';
import 'package:flutter_fun_zjversion/provider/view_state_model.dart';
import 'package:flutter_fun_zjversion/provider/view_state_refresh_list_model.dart';
import 'package:flutter_fun_zjversion/service/wan_android_repositoty.dart';

import 'login_model.dart';

class FavouriteListModel extends ViewStateRefreshListModel<Article>{

  LoginModel loginModel;

  FavouriteListModel({this.loginModel});

  @override
  void setUnAuthorized() {
    loginModel.loginOut();
    super.setUnAuthorized();
  }

  @override
  Future<List<Article>> loadData({int pageNum}) async {
    return await WanAndroidRepository.fetchCollectList(pageNum);
  }

}

/// 收藏/取消收藏
class FavouriteModel extends ViewStateModel {
  GlobalFavouriteStateModel globalFavouriteModel;

  FavouriteModel({@required this.globalFavouriteModel});

  collect(Article article) async {
    setBusy(true);
    try {
      // article.collect 字段为null,代表是从我的收藏页面进入的 需要调用特殊的取消接口
      if (article.collect == null) {
        await WanAndroidRepository.unMyCollect(
            id: article.id, originId: article.originId);
        globalFavouriteModel.removeFavourite(article.originId);
      } else {
        if (article.collect) {
          await WanAndroidRepository.unCollect(article.id);
          globalFavouriteModel.removeFavourite(article.id);
        } else {
          await WanAndroidRepository.collect(article.id);
          globalFavouriteModel.addFavourite(article.id);
        }
      }
      article.collect = !(article.collect ?? true);
      setBusy(false);
    } catch (e, s) {
      handleCatch(e, s);
    }
  }
}



class GlobalFavouriteStateModel extends ChangeNotifier{
  static final Map<int,bool> _map = Map();

  static refresh(List<Article> list){
    list.forEach((article){
      if(_map.containsKey(article.id)){
        _map[article.id] = article.collect;
      }
    });
  }

  addFavourite(int id){
    _map[id] = true;
    notifyListeners();
  }

  removeFavourite(int id){
    _map[id] = false;
    notifyListeners();
  }


  /// 用于切换用户后,将该用户所有收藏的文章,对应的状态置为true
  replaceAll(List ids) {
    _map.clear();
    ids.forEach((id) => _map[id] = true);
    notifyListeners();
  }

  contains(id){
    return _map.containsKey(id);
  }

  operator [](int id) {
    return _map[id];
  }

}